<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Common\ApiHelper;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoginController
{
    //加载登录页面
    public function index()
    {
        return view('login.index');
    }

    public function loginOperation(Request $request)
    {
        $param = $request->all();
        $username = $param['username'] ?? uniqid(1);
        $user = User::query()->where('username', $username)->first();
        if (!$user) {
            //创建用户
            DB::beginTransaction();
            try {
                $user = User::query()->create([
                    'username' => $username
                ]);
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                Log::info('创建用户-失败', ['data' => $exception->getMessage()]);
                return redirect()->route('login');
            }
        }
        session(['user' => [
            'id' => $user->id,
            'username' => $user->username
        ]]);
        return redirect()->route('im.indexList');
    }
}
